package com.ctgu.demo.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(@Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
        // 创建 RedisTemplate 对象
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 使用 Jackson2JsonRedisSerializer 处理值序列化，确保对象正确序列化到 Redis
        Jackson2JsonRedisSerializer<Object> jacksonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        // 设置 Key 和 Value 的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());        // 设置键的序列化方式为 String
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());    // 哈希键的序列化
        redisTemplate.setValueSerializer(jacksonSerializer);                // 设置值的序列化方式为 Jackson
        redisTemplate.setHashValueSerializer(jacksonSerializer);            // 哈希值的序列化

        return redisTemplate;
    }
}